package com.itheima.question.controller;

import com.itheima.Result;
import com.itheima.common.contants.RedisPicConstants;
import com.itheima.question.config.FastDFSClientUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/question")
@Api(value = "文件上传接口",tags="admin_user",description = "用于实现各种文件上传")
public class FileController {

    @Autowired
    FastDFSClientUtil fastDFSClientUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try {
            //判断文件是否存在
            if(file == null){
                throw new RuntimeException("文件不存在");
            }
            String fileId = fastDFSClientUtil.uploadFile(file);
            redisTemplate.opsForSet().add(RedisPicConstants.ALL_PIC,fileId);
            return new Result(true,"上传图片成功",fileServerUrl+fileId);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result(false,"文件上传失败",null);

    }
    @GetMapping("/del")
    public Result delFile(String fileId){
        try {
            fastDFSClientUtil.delFile(fileId);
            return new Result(true,"删除成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"删除失败",null);
        }

    }
}
